<?php

namespace App\Http\Resources\Api;

use App\Models\UserCount;
use Illuminate\Http\Resources\Json\Resource;

class Account extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray($request)
    {
        /** @var \App\Models\User $user */
        $user = $this->resource;

        $user->user_count;
        if (!$user->user_count) {
            UserCount::firstOrCreate(['user_id' => app('auth')->id()]);
            $user->user_count;
        }

        $user->user_count->win_percentage = $user->user_count->total_game == 0 ? 0 : ceil($user->user_count->total_winning / $user->user_count->total_game * 1000) / 1000;

        $userCount = $user->user_count->toArray();

        return object_only($user, [
            'id', 'nickname', 'avatar', 'gender',
        ]) + $userCount;
    }
}
